import time
from rest_framework import serializers

from goods.models import Goods
from goods.serializers import GoodListSerializer, OrderCardGoodsSerializer
from hf_mall.settings import private_key_path, ali_pub_key_path
from trade.models import ShoppingCart, OrderInfo, OrderGoods
from utils.alipay import AliPay


class ShopCartDetailSerializer(serializers.ModelSerializer):
    goods = GoodListSerializer(many=False, )

    class Meta:
        model = ShoppingCart
        fields = '__all__'


class ShopCartSerializer(serializers.Serializer):
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    nums = serializers.IntegerField(required=True, label="数量", min_value=1,
                                    error_messages={
                                        "min_value": "商品数量不能小于一",
                                        "required": "请选择购买数量"
                                    })
    goods = serializers.PrimaryKeyRelatedField(required=True, label="商品", queryset=Goods.objects.all())
    isCheck = serializers.BooleanField(required=True, label="是否选中")

    def create(self, validated_data):
        user = self.context["request"].user
        nums = validated_data["nums"]
        goods = validated_data["goods"]

        existed = ShoppingCart.objects.filter(user=user, goods=goods)

        if existed:
            existed = existed[0]
            existed.nums += nums
            existed.save()
        else:
            existed = ShoppingCart.objects.create(**validated_data)

        return existed

    def update(self, instance, validated_data):
        if validated_data.__contains__('nums'):
            instance.nums = validated_data['nums']
        if validated_data.__contains__('isCheck'):
            instance.isCheck = validated_data['isCheck']
        instance.save()
        return instance


class OrderGoodsSerializer(serializers.ModelSerializer):
    good = OrderCardGoodsSerializer(many=False)

    class Meta:
        model = OrderGoods
        fields = '__all__'


class OrderSerializer(serializers.ModelSerializer):
    goods = serializers.ListField(label='商品', write_only=True, )
    user = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    order_sn = serializers.CharField(read_only=True, )
    trade_no = serializers.CharField(read_only=True, )
    pay_status = serializers.CharField(read_only=True, )
    pay_time = serializers.CharField(read_only=True, )
    add_time = serializers.CharField(read_only=True, )
    alipay_url = serializers.SerializerMethodField(read_only=True)

    def get_alipay_url(self, obj):
        alipay = AliPay(
            appid="2021000117660243",
            app_notify_url="http://127.0.0.1:8080/alipay/return/",
            app_private_key_path=private_key_path,
            alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            debug=True,  # 默认False,
            return_url="http://127.0.0.1:8080/order/"
        )

        url = alipay.direct_pay(
            subject=obj.order_sn,
            out_trade_no=obj.order_sn,
            total_amount=obj.order_mount,
        )
        re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)

        return re_url

    def generate_order_sn(self):
        # 当前时间+userid+随机数
        from random import Random
        random_ins = Random()
        order_sn = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       userid=self.context["request"].user.id,
                                                       ranstr=random_ins.randint(10, 99))
        return order_sn

    def validate(self, attrs):
        attrs['order_sn'] = self.generate_order_sn()
        del attrs['goods']
        return attrs

    class Meta:
        model = OrderInfo
        fields = ('id', 'user', 'order_mount', 'address', 'signer_name', 'singer_mobile', 'goods', 'order_sn',
                  'trade_no', 'pay_status', 'pay_time', 'add_time', 'alipay_url')


class OrderListSerializer(serializers.ModelSerializer):
    commodities = OrderGoodsSerializer(many=True)
    # alipay_url = serializers.SerializerMethodField(read_only=True)
    #
    # def get_alipay_url(self, obj):
    #     return pay.direct_pay(obj)

    # def get_alipay_url(self, obj):
    #     alipay_client_config = AlipayClientConfig(settings.ALIPAY_DEBUG)
    #     alipay_client_config.app_id = settings.ALIPAY_APPID
    #     alipay_client_config.app_private_key = settings.private_key_path
    #     alipay_client_config.alipay_public_key = settings.ali_pub_key_path
    #     client = DefaultAlipayClient(alipay_client_config)
    #     model = AlipayTradeWapPayModel()
    #     model.out_trade_no = obj.order_sn
    #     model.total_amount = obj.order_mount
    #     model.subject = obj.order_sn
    #     model.product_code = "QUICK_WAP_WAY"
    #     request = AlipayTradeWapPayRequest(biz_model=model)
    #     request.return_url = "http://127.0.0.1:8000/payment_success/"
    #     request.notify_url = "http://127.0.0.1:8000/payment_notify/"
    #     alipay_url = client.page_execute(request, "GET")
    #     return alipay_url

    # def get_alipay_url(self, obj):
    #     alipay = AliPay(
    #         appid="",
    #         app_notify_url="http://127.0.0.1:8000/alipay/return/",
    #         app_private_key_path=private_key_path,
    #         alipay_public_key_path=ali_pub_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
    #         debug=True,  # 默认False,
    #         return_url="http://127.0.0.1:8080/order/"
    #     )
    #
    #     url = alipay.direct_pay(
    #         subject=obj.order_sn,
    #         out_trade_no=obj.order_sn,
    #         total_amount=obj.order_mount,
    #     )
    #     re_url = "https://openapi.alipaydev.com/gateway.do?{data}".format(data=url)
    #
    #     return re_url

    class Meta:
        model = OrderInfo
        fields = '__all__'
